package com.miyu.client1.service.book.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.miyu.client1.pojo.Book;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class queryTask implements Callable<JSONArray> {

    private JSONObject jo;
    private static Pattern pattern = Pattern.compile("<a[^>]*href=(\\\"([^\\\"]*)\\\"|\\'([^\\']*)\\'|([^\\\\s>]*))[^>]*>(.*?)</a>");
    String url="";
    String source="";
    String type="";
    String search="";

    //  {"root":"https://www.biquge5200.com","index":"https://www.biquge5200.com/modules/article/search.php?searchkey=","source":"biquge5200","type":"GET"}
    public queryTask(JSONObject t) {
        this.jo = t;
    }

    @Override
    public JSONArray call() throws Exception {
        url = jo.getString("index");
        source = jo.getString("source");
        type = jo.getString("type");
        search = jo.getString("search");
        List<Book> bookDtos = null;
        JSONArray ja = new JSONArray();
        try {
            Document document = null;
            if (type.equals("GET")) {
                document = Jsoup.connect(url + search).get();
            } else {
                Connection connect = Jsoup.connect(url);
                connect.data("keyword", search);
                document = connect.post();
            }
            Element element = document.select("tbody").get(0);
            Elements trs = element.getElementsByTag("tr");
            List<Element> trss = trs.stream().filter(element1 -> !element1.text().isEmpty()).collect(Collectors.toList());
//            bookDtos = get1(trss, pattern);
            ja = get1(trss, pattern);
        } catch (IOException e) {
            e.printStackTrace();
        }


        return ja;
    }

    public static JSONArray get1(List<Element> tbody, Pattern pattern) {
        List<Book> bookDtos = new ArrayList<>(tbody.size());
        JSONArray ja = new JSONArray();

        Map<String, Integer> map = new HashMap<>(10);
        tbody.forEach(tr -> {
            List<Node> nodes = tr.childNodes().stream().filter(node -> !node.toString().trim().isEmpty()).collect(Collectors.toList());
            Elements td = tr.getElementsByTag("td");
            String s1 = nodes.toString();
            for (int i = 0; i < nodes.size(); i++) {
                String node = nodes.get(i).toString();
                if (node.matches("(.*)文章名称(.*)") || node.matches("(.*)书名(.*)")) {
                    map.put("bookName", i);
                    continue;
                }
                if (node.matches("(.*)作者(.*)")) {
                    map.put("author", i);
                    return;
                }
            }
            JSONObject jo = new JSONObject();
            Book book = new Book();
            String href = "";
            String reg = ".*</a>.*";
            if (s1.matches(reg)) {
                Matcher matcher = pattern.matcher(s1);
                if (matcher.find()) {
                    href = matcher.group(1);
                    String nameCode = href.substring(href.lastIndexOf(".com")+5,href.length()-2);
                    if("ascript:void(0)".equals(nameCode)){
                        return;
                    }
                    book.setBookCode(nameCode);
                    jo.put("bookCode",nameCode);
                }
            }
            jo.put("hrefs",href.replace("\"",""));
            jo.put("bookName",td.get(map.get("bookName")).text());
            jo.put("author",td.get(map.get("author")).text());
            book.setBookName(td.get(map.get("bookName")).text());
            book.setBookAuthor(td.get(map.get("author")).text());
            bookDtos.add(book);
            ja.add(jo);
        });
        return ja;
    }
}
